package com.usian.admin.gateway.filter;

import com.alibaba.nacos.client.utils.StringUtils;
import com.usian.jwt.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Component
public class AdminGatewayFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //判断登录路径
        if (request.getURI().getPath().contains("/login/in")) { //contains包含
            return chain.filter(exchange);
        }
        //获取token
        String token = request.getHeaders().getFirst("token");
        //判断token
        if (StringUtils.isBlank(token)) {
            //返回错误提示
            String str = "{\"errorMessage\":\"dont have token\"}";
            response.writeWith(Flux.just(response.bufferFactory().wrap(str.getBytes())));
        }
        //检验token合法性 最消耗时间
        Claims claims = AppJwtUtil.getClaimsBody(token);
        //检验是否过期
        int i = AppJwtUtil.verifyToken(claims);
        if (i == 0 || i == -1) {
            //将用户id放到请求头中
            Integer id = (Integer) claims.get("id");
            request.mutate().headers(httpHeaders -> {
                httpHeaders.set("userId", id + "");
            }).build();
            //token快过期了
            if (i == 0) {
                String newtoken = AppJwtUtil.getToken(id.longValue());
                request.mutate().headers(httpHeaders -> {
                    httpHeaders.set("newtoken", newtoken);
                }).build();
            }
            //把重新构建request的放在交换机中
            exchange.mutate().request(request).build();
        } else {
            String str = "{\"errorMessage\":\"dont have token\"}";
            response.writeWith(Flux.just(response.bufferFactory().wrap(str.getBytes())));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
